/*
 * @Author: xiaosihan 
 * @Date: 2024-02-27 11:41:40 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-03-10 14:01:29
 */


import { Group, AxesHelper } from "three";
import Building from "../Building/Building";
import { autorun } from "mobx";
import homeStore from "@views/home/homeStore";
import windowApi from "@service/windowApi";
import { BuildWindowData, WindowTypeData } from "@views/home/type";
import { clone, cloneDeep } from "lodash";

// 楼房组对象
export default class BuildGroup extends Group {
    constructor() {
        super();
    }

    declare children: Array<Building>;

    dispose = autorun(async () => {
        const { builds, activeBuildId } = homeStore;
        const b = builds.find(b => b.buildId === activeBuildId);
        this.children.map(b => (b.visible = false));

        if (b) {
            const buildData = await windowApi.getBuildWindow(b.buildId); // 获取窗户安装转态
            const windowType = await windowApi.getWindowType(b.buildId); // 获取窗户安装转态

            homeStore.setBuildData(buildData.data.data);
            homeStore.setWindowType(windowType.data.data);

            // 判断是否有地下室
            const wt = clone(windowType.data.data);
            const underground = wt.filter((w: any) => /$(-|负)/.test(w.floorNo));
            this.position.setY(-0.6 + (underground.length * 0.3));

            if (this.children[0]) {
                this.children[0].visible = true;
                this.children[0].uuid = b.buildId;
                this.children[0].setBuildNo(b.buildNo);
                this.children[0].setData(buildData.data.data as Array<BuildWindowData>, windowType.data.data as Array<WindowTypeData>);
            } else {
                const build = new Building();
                await build.awaitLoaded();
                build.uuid = b.buildId;
                build.setBuildNo(b.buildNo);
                build.setData(buildData.data.data as Array<BuildWindowData>, windowType.data.data as Array<WindowTypeData>);
                // build.position.set(0, -0.667, 0);
                this.add(build);
            }
        }

        await new Promise(resolve => setTimeout(resolve, 100));
        await new Promise(resolve => requestAnimationFrame(resolve));
        await new Promise(resolve => requestAnimationFrame(resolve));
        await new Promise(resolve => requestAnimationFrame(resolve));

        this.dispatchEvent({ type: "loaded" } as never);
    });

}